<template>
  <a-card>
    <template #title>
      <a-form layout="vertical">
        <a-row :gutter="24">
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('平台订单号')">
              <a-input v-model:value="page.platOrderId" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('商户订单号')">
              <a-input v-model:value="page.orderId" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('客户名字')">
              <a-input v-model:value="page.userName" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('身份证号码')">
              <a-input v-model:value="page.idCard" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('银行名称')">
              <a-input v-model:value="page.bankName" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('收款账号')">
              <a-input v-model:value="page.bankNo" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item label="cci">
              <a-input v-model:value="page.cci" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('分单时间')">
              <a-range-picker style="width: 100%" v-model:value="page.createTime" valueFormat="YYYY-MM-DD"
                              format="YYYY-MM-DD"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">{{ $t('重置') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <a-table row-key="id" :data-source="tableData" :columns="tableColumn"
             :scroll="{x:1000}"
             :pagination="pagination">
      <template #handle="{record}">
        <a-button type="link" @click="rowClick('success',record)" v-permiss="['pay-success']">{{
            $t('打款成功')
          }}
        </a-button>
        <a-button type="link" @click="rowClick('error',record)" v-permiss="['pay-error']">{{ $t('打款失败') }}</a-button>
      </template>
    </a-table>
    <!--     打款成功-->
    <a-modal v-model:visible="visibleSuccess" :title="$t('打款成功')" @ok="successConfirm"
             @cancel="successClose()"
             :confirm-loading="confirmLoading">
      <a-form ref="successRefForm" :model="successForm" :rules="rulesForm" :label-col="{span:5}">
        <a-form-item :label="$t('平台订单号')">
          {{ tableRows.platOrderId }}
        </a-form-item>
        <a-form-item :label="$t('客户姓名')">
          {{ tableRows.userName }}
        </a-form-item>
        <a-form-item :label="$t('身份证号码')">
          {{ tableRows.idCard }}
        </a-form-item>
        <a-form-item :label="$t('打款金额')">
          {{ tableRows.payAmount }}
        </a-form-item>
        <a-form-item :label="$t('打款银行')" name="offlinePayId">
          <a-select style="width:220px" v-model:value="successForm.offlinePayId">
            <a-select-option v-for="item in bankList" :key='item.offlinePayId' :value="item.offlinePayId">{{
                item.alias
              }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('打款时间')" name="paymentTime">
          <a-date-picker v-model:value="successForm.paymentTime" valueFormat="YYYY-MM-DD hh:mm:ss" show-time
                         allowClear/>
        </a-form-item>
        <a-form-item :label="$t('交易流水')" name="transactionId">
          <a-input v-model:value="successForm.transactionId" allowClear/>
        </a-form-item>
        <a-form-item :label="$t('上传凭证')" name="voucher">
          <a-upload
              name="avatar"
              list-type="picture-card"
              :custom-request="uploadVoucher"
              :show-upload-list="false"
              accept="image/*"
              class="avatar-uploader"
          >
            <img v-if="successForm.voucher" :src="successForm.voucher" class="imgUrl" alt="avatar"/>
            <div v-else>
              <plus-outlined></plus-outlined>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
    <!--     打款失败-->
    <a-modal v-model:visible="visibleError" :title="$t('打款失败')" @ok="errorConfirm" :confirm-loading="confirmLoading"
             @cancel="errorClose()"
    >
      <a-form ref="errorRefForm" :model="errorForm" :rules="rulesForm" :label-col="{span:5}">
        <a-form-item :label="$t('平台订单号')">
          {{ tableRows.platOrderId }}
        </a-form-item>
        <a-form-item :label="$t('客户姓名')">
          {{ tableRows.userName }}
        </a-form-item>
        <a-form-item :label="$t('身份证号码')">
          {{ tableRows.idCard }}
        </a-form-item>
        <a-form-item :label="$t('打款失败原因')" name="statusDesc">
          <a-select style="width:220px" v-model:value="errorForm.statusDesc" allowClear>
            <a-select-option v-for="item in failureReasonList" :key='item' :value="item">{{ item }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('备注')" name="remark">
          <a-textarea :rows="4" v-model:value="errorForm.remark"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import {onMounted, reactive, ref, toRefs, computed} from 'vue'
import {
  fetchPaymentAgencyList,
  paymentOfflineSuccess,
  paymentOfflineFail,
  fetchPaymentFailureReason
} from "../../../api/payment"
import {offlinePayList} from "../../../api/system"
import {message, Modal} from "ant-design-vue";
import i18n from "../../../locale";

const $t = i18n.global.t
import {PlusOutlined} from '@ant-design/icons-vue'
import {uploadImage} from "../../../api/capital";

const tableColumn = [
  {title: $t('平台订单号'), dataIndex: 'platOrderId', width: 100, align: 'center'},
  {title: $t('商户订单号'), dataIndex: 'orderId', width: 100, align: 'center'},
  {title: $t('客户名字'), dataIndex: 'userName', width: 100, align: 'center'},
  {title: $t('身份证号码'), dataIndex: 'idCard', width: 150, align: 'center'},
  {title: $t('银行名称'), dataIndex: 'bankName', width: 150, align: 'center'},
  {title: $t('收款账号'), dataIndex: 'bankNo', width: 100, align: 'center'},
  {title: 'cci', dataIndex: 'cci', width: 100, align: 'center'},
  {title: $t('到账金额'), dataIndex: 'payAmount', width: 100, align: 'center'},
  {title: $t('分单时间'), dataIndex: 'createTime', width: 100, align: 'center'},
  {title: $t('操作'), width: 200, align: 'center', fixed: 'right', slots: {customRender: 'handle'}},
]
export default {
  name: "PaymentDistributionAllList",
  components: {
    PlusOutlined,
  },
  setup() {
    const successRefForm = ref(null)
    const errorRefForm = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      tableRows: {},
      visibleSuccess: false,
      visibleError: false,
      successForm: {
        offlinePayId: null,
        paymentTime: null,
        transactionId: null,
        voucher: null
      },
      successLoading: false,
      errorForm: {
        statusDesc: null,
        remark: null
      },
      bankList: [],
      rulesForm: {
        offlinePayId: {required: true, message: $t('请选择'), trigger: 'change', type: 'number'},
        paymentTime: {required: true, message: $t('请选择'), trigger: 'change'},
        transactionId: {required: true, message: $t('不能为空'),},
        voucher: {required: true, message: $t('请选择'), trigger: 'change'},
        remark: {
          required: false, validator: (rules, value) => {
            if (state.errorForm.statusDesc === 'otro' && !value) {
              return Promise.reject($t('请输入备注'))
            }
            return Promise.resolve()
          }
        }
      },
      confirmLoading: false,
      failureReasonList: []
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + $t('条'),
      onChange: (value) => {
        state.page.pageNum = value
        methods.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        methods.getTableData()
      }
    }))
    const methods = {
      async getTableData() {
        const [assignOrderTimeStart, assignOrderTimeEnd] = state.page.createTime || []
        const [paymentTimeStart, paymentTimeEnd] = state.page.paymentTime || []
        const params = {
          ...state.page,
          assignOrderTimeStart, assignOrderTimeEnd, paymentTimeStart, paymentTimeEnd,
          createTime: undefined,
          paymentTime: undefined
        }
        const res = await fetchPaymentAgencyList(params)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        methods.getTableData()
      },
      rowClick(type, row) {
        state.tableRows = {...row}
        if (type === 'success') {
          offlinePayList({type: 1}).then(res => {
            state.bankList = res.data.list
          })
          state.visibleSuccess = true
        } else {
          fetchPaymentFailureReason().then(res => {
            state.failureReasonList = res.data
          })
          state.visibleError = true
        }
      },
      // 打款成功提交
      successConfirm() {
        successRefForm.value.validate().then(async v => {
          if (v) {
            const params = {
              ...state.successForm,
              id: state.tableRows.id,
            }
            state.confirmLoading = true
            const res = await paymentOfflineSuccess(params)
            if (res.code === 200) {
              message.success($t('操作成功'))
              state.visibleSuccess = false
              methods.getTableData()
            }
            state.confirmLoading = false
          }
        })
      },
      // 打款失败提交
      errorConfirm() {
        errorRefForm.value.validate().then(async v => {
          if (v) {
            const params = {
              ...state.errorForm,
              id: state.tableRows.id,
            }
            state.confirmLoading = true
            const res = await paymentOfflineFail(params)
            if (res.code === 200) {
              message.success($t('操作成功'))
              state.visibleError = false
              methods.getTableData()
            }
            state.confirmLoading = false
          }
        })
      },
      successClose() {
        successRefForm.value.resetFields()
      },
      errorClose() {
        errorRefForm.value.resetFields()
      },
      async uploadVoucher(data) {
        const hide = message.loading($t('上传中...'), 0)
        const formData = new FormData()
        formData.append('file', data.file)
        const res = await uploadImage(formData)
        if (res.code === 200) {
          state.successForm.voucher = res.data
        }
        hide()
      }
    }
    onMounted(() => {
      methods.getTableData()
    })
    return {
      successRefForm,
      errorRefForm,
      pagination,
      tableColumn,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
